/**
 * Created by hillchen on 2018/1/4 0004.
 */
const utils =require('loader-utils');
const fs = require('fs');
const path = require('path');

module.exports = function (source) {
  let viewLoader = {
    views:new Set,
    seekFilePaths (_basePath,pathAlias,fileExtension) {
      let that = this;
      let files = fs.readdirSync(_basePath);
      //遍历读取到的文件列表
      files.forEach(function(filename){
        //获取当前文件的绝对路径
        let filedir = path.join(_basePath,filename);

        //根据文件路径获取文件信息，返回一个fs.Stats对象
        let stats = fs.statSync(filedir);
        if(stats.isFile()){
          if(filedir.endsWith(fileExtension)){
            let viewPath = "./"+path.join(pathAlias,filename);
            viewPath = viewPath.replace(/\\/g,"/");
            that.views.add(viewPath);
            console.log(that.views.size);
            console.log(viewPath);
          }
        }
        if(stats.isDirectory()){
          that.seekFilePaths(filedir,path.join(pathAlias,filename),fileExtension);
        }
      });
    },
    loadViews (_basePath,pathAlias) {
      let fileExtension = ".vue"
      this.seekFilePaths(_basePath,pathAlias,fileExtension);
      console.log(this.views);
    }
  }

  console.log(source);
  let options = utils.getOptions(this);
  let sourcePaht =options.sourcePaht;
  let viewsRelativePath = options.viewsRelativePath;

  console.log(sourcePaht);
  console.log(viewsRelativePath);

  let basePath = sourcePaht + viewsRelativePath;

  console.log(viewsRelativePath);
  viewLoader.loadViews(basePath,".");
  let views = viewLoader.views;
  console.log(views.size);
  let nextLineStr = "\r\n";
  let importStr = "";
  let exportStr = "export default {";
  let viewIndex = 0;

  for(let view of views){
    console.log("viewIndex:"+viewIndex+",view:"+view);
    let viewName = "view"+viewIndex;
    importStr += ("import "+viewName+" from '"+view+"'");
    importStr += nextLineStr;
    if(viewIndex != 0 ){
      exportStr += ",";
    }
    exportStr += ("'"+view+"':"+viewName);
    viewIndex ++;
  }
  exportStr +="}";
  console.log(importStr);
  console.log(exportStr);
  let content = importStr + nextLineStr + exportStr;
  console.log(content);
  return content;
};


